<template>
	<view class="index-box" :style="{ '--color': vuex_config.themeColor1, '--price': vuex_config.price }">
		<template v-if="dataForm.pk_id ? true : false">
			<view class="prod_img">
				<sww-swipe :list="swipeList" indicatorDots autoplay @onPlayVideo="onPlayVideo"></sww-swipe>
				<sold-out v-if="dataForm.stock <= 0"></sold-out>
			</view>
			<view class="content-box">
				<!-- 限时抢购计时器 -->
				<view class="flash-times flex-tb" v-if="dataForm.type == 2 && prodState.type !== 3">
					<view class="ft_icon iconfont iconfont-e656"></view>
					<text class="">限时抢购</text>
					<view class="ml-auto">{{ prodState.msg }}</view>
					<template v-if="prodState.times ? true : false">
						<view>：</view>
						<view v-if="timeObj.day > 0">{{ timeObj.day }}天</view>
						<view class="ft-time">{{ timeObj.hours }}</view>
						<view class="ft-time">{{ timeObj.minute }}</view>
						<view class="ft-time">{{ timeObj.second }}</view>
					</template>
				</view>
				<!-- 基本信息 -->
				<view class="prod_box">
					<view class="prod-title u-font-30 fw-bold">{{ dataForm.name }}</view>
					<view class="title_sen" v-if="vuex_config.subtitle == 1 && dataForm.title">{{ dataForm.title }}
					</view>
					<view class="prod-price u-flex u-border-bottom">
						<!-- 价格区间 start-->
						<view>
							<text class="u-font-24 price_color u-m-r-5">￥</text>
							<view style="display: inline;" class="u-font-36 fw-bold price_color u-m-r-15 pricearr">
								<view style="display: inline;" v-if="dataForm.minPrice ? true : false">
									{{ $price(dataForm.minPrice) }} - {{ $price(dataForm.maxPrice) }}
								</view>
								<text v-else>{{ $price(dataForm.price) }}</text>
							</view>
							<!-- 会员价格  -->
							<block
								v-if="showVip && dataForm.vip_price  &&  $price(dataForm.price) != $price(dataForm.vip_price) ">
								<text class="u-font-25 sww-tp u-m-r-5">vip</text>
								<text class="u-font-20 sww-tp ">￥</text>
								<text class="u-font-25 sww-tp">{{ $price(dataForm.vip_price) }}</text>
							</block>
							<!-- 分销商返佣 -->
							<block v-else-if="vuex_user.type == 2 && dataForm.rebate > 0 && vuex_user.commission > 0 ">
								<text class="u-font-25 sww-tp u-m-r-5">分享赚</text>
								<text class="u-font-20 sww-tp ">￥</text>
								<text
									class="u-font-25 sww-tp">{{ $rebateNum(dataForm.rebate, vuex_user.commission) }}</text>
							</block>
							<!-- 市场价 -->
							<text class="u-font-24 u-m-l-10 c-99 td-lt"
								v-if="dataForm.market_price > 0 && !dataForm.minPrice">￥{{ $price(dataForm.market_price) }}</text>
						</view>
						<!--    价格区间 end-->
						<text class="u-font-24 c-99 ml-auto"
							v-if="vuex_config.sales_volume == 1 && dataForm.order_count > 0">
							<text>已售</text>
							<text>{{ $price(dataForm.order_count) }}</text>
						</text>
					</view>
					<u-cell-item :arrow="false" hover-class="none">
						<view class="u-flex u-row-between u-font-24">
							<view class="">快递: {{ getLogistic || 0 }}</view>
							<view class="" v-if="vuex_config.reading_volume == 1">浏览人数: {{ dataForm.view || 0 }}</view>
						</view>
					</u-cell-item>
					<u-cell-item title="选择规格" @click="showSpec('')"></u-cell-item>
					<u-cell-item v-if="dataForm.fk_supplier_id" :title="dataForm.supplier_name || '店铺'" value="进入店铺"
						@click="openshop(dataForm.fk_supplier_id)">
						<view style="margin-right: 10rpx;font-size: 38rpx;" slot="icon" class="iconfont iconfont-e736">
						</view>
					</u-cell-item>
				</view>
				<view class="prod_box" style="margin-top: 20rpx; border-radius: 0;" v-if="dataList.length>0">
					<view class="supplier-box">
						<view class="box-left">
							<text class="u-font-28">用户评价</text>
						</view>
						<view class="box-right"
							@click="$linkTo(`/package/product/comment/index?prodId=${dataForm.pk_id}&id=1`)">
							<view style="margin-right: 10rpx;">全部评价</view>
							<u-icon name="e775" size="24" color="#999" custom-prefix="iconfont"></u-icon>
						</view>
					</view>
					<view class="commentbox">
						<view class="data-list">
							<view class="comment-item mb-20" v-for="(item, index) in dataList" :key="index">
								<view class="ci-t flex-tb">
									<view class="ci-avatar">
										<image :src="item.headimgurl"></image>
									</view>
									<view class="ci-info flex-c">
										<view class="ci-name f-28">{{ item.nickname }}</view>
										<view class="ci-date c-99">{{ item.date_creation | formTime }}</view>
									</view>
								</view>
								<view class="ci-b f-28 mt-10">{{ item.content }}</view>
								<view class="ci-img">
									<image class="ci-img-item" mode="aspectFill" v-for="(items,idx) in item.img"
										:src="items" @click="prewImg(idx, item.img)" :key="mindex"></image>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="to_mini" v-if="isToMini">
					<view class="mini_btn" @click="goToMini">查看唐媒名片</view>
				</view>
				<!-- 产品详情 -->
				<block v-if="dataForm.details">
					<view class="prod_box u-m-t-10">
						<u-cell-item :border-bottom="false" :arrow="false">
							<view class="fw-bold" slot="title" hover-class="none">商品详情</view>
						</u-cell-item>
						<u-parse :html="dataForm.details"></u-parse>
					</view>
				</block>
				<!-- 购买须知 -->
				<block v-if="dataForm.descript">
					<view class="prod_box u-m-t-10">
						<u-cell-item :border-bottom="false" :arrow="false">
							<view class="fw-bold" slot="title" hover-class="none">购买须知</view>
						</u-cell-item>
						<u-parse :html="dataForm.descript"></u-parse>
					</view>
				</block>
			</view>
			<!--  底部  -->
			<sww-goods-action>
				<button class="goods-action-icon u-reset-button" @click="$linkTo('index')">
					<view class="">
						<u-icon name="e736" size="36" color="#666666" custom-prefix="iconfont"></u-icon>
					</view>
					<view class="bb-text">首页</view>
				</button>
				<button class="goods-action-icon u-reset-button" @click="collectChange">
					<!-- <block v-if="isFavorite">
					<view class="sww-tc-c"><u-icon name="e732" size="36" custom-prefix="iconfont"></u-icon></view>
				</block> -->
					<!-- <block v-else> -->
					<view :class="[isFavorite ? 'active' : '']">
						<u-icon :name="isFavorite ? 'e732' : 'e733'" size="36" color="#666666" custom-prefix="iconfont">
						</u-icon>
					</view>
					<!-- </block> -->
					<view class="bb-text">收藏</view>
				</button>
				<button class="goods-action-icon u-reset-button" @click="linkToCart">
					<view class="">
						<u-icon name="e73d" size="36" color="#666666" custom-prefix="iconfont"></u-icon>
					</view>
					<view class="bb-text">购物车</view>
					<view class="bb-num" v-if="false">1</view>
				</button>
				<view class="goods-action-btn-wrap">
					<view class="goods-action-btn" @click="showSpec('cart')" v-if="dataForm.type == 1">加入购物车</view>
					<view class="goods-action-btn" @click="showSpec('buy')">立即购买</view>
				</view>
			</sww-goods-action>
		</template>
		<!-- 规格弹窗 -->
		<sww-goods-spec v-model="specVisible" :params="specParams" :prodInfo="dataForm" type="0" @change="buyNow"
			@vipChange="showVip = true"></sww-goods-spec>
		<sww-login></sww-login>
		<sww-sidebar :scroll-top="scrollTop" :prod-info="{ ...dataForm, prodType: 1 }" share
			:contact="vuex_config.has_contact"></sww-sidebar>
	</view>
</template>
<script>
	import {
		uniModal,
		uniNavigate,
		uniToast
	} from '@/utils/uniPromise';
	import {
		getProdStatus
	} from '@/module/product/prodMet';
	import {
		mapState
	} from 'vuex';
	import {
		pageShare
	} from '@/mixins/pageShare';
	import {
		timeMiXin
	} from '@/mixins/timemixin';
	import {
		sideBarMixin
	} from '@/components/sww-sidebar';
	import {
		formatDate,
		countTime,
		isAfter,
		isBefore
	} from '@/utils/moment/index.js';
	import {
		payOrder
	} from '@/utils/weixinPay.js';
	import soldOut from '../../components/soldOut.vue';
	// // #ifdef H5
	// var wx = require('jweixin-module')
	// // #endif
	export default {
		mixins: [pageShare, sideBarMixin, timeMiXin],
		data() {
			return {
				showVip: false, // 是否允许显示并使用会员价格
				timeObj: {}, // 倒计时时间对象
				time: null, // 倒计时计算器
				swipeList: [], //轮播
				prodState: {
					type: 0, // 0未开始，1进行中，2已结束
					times: 0 // 初始化查询是，距离下个状态的时间戳差值
				}, //产品状态
				dataForm: {}, //产品详情
				dataList: [], //评论列表
				shareParams: {},
				paramsObj: {}, //页面栈传值用
				specVisible: false, //规格弹框
				specParams: {
					buyType: '',
					prodId: '', //产品ID
					stockId: '', //产品规格ID
					cartId: '', //购物车ID
					num: 0 //产品规格购买数量
				},
				commentList: null,
				browTime: 0
			};
		},
		components: {
			soldOut
		},
		computed: {
			...mapState(['vuex_business']),
			isToMini() {
				return (this.dataForm.title || '').includes('ToMini');
			},
			getLogistic() {
				// 获取运费情况
				if (this.dataForm.product_freight) {
					return '根据配送区域计算';
				} else if (this.dataForm.express_num <= 1) {
					return '免运费';
				} else if (this.dataForm.express_num > 1) {
					return this.dataForm.express_num + '件起免运费';
				}
			},
			isFavorite() {
				return (this.dataForm && this.dataForm.isFavorite == 1);
			}
		},
		onLoad(options) {
			if (options.id) {
				if (this.time) {
					// 重新跳转到已存在的详情页时
					clearTimeout(this.time);
				}
				this.initPage(options.id);
				this.getBrowTime();
			} else {
				this.$linkTo('index');
			}
		},
		onShareAppMessage: function() {
			return this.getShareAppMessage();
		},
		onShareTimeline: function() {
			let obj = this.getShareTimeline();
			return obj;
		},
		onUnload() {
			if (this.time) {
				clearTimeout(this.time);
			}
			if (this.browTime) {
				this.addBrow(this.dataForm.pk_id);
			}
		},
		filters: {
			formTime(time) {
				return formatDate(time, 'YYYY-MM-DD HH:mm:ss');
			}
		},
		methods: {
			// 记录开始浏览时间
			getBrowTime() {
				this.browTime = new Date().getTime();
			},
			openshop(id) {
				this.$to(`/package/index/shopDetail/index?id=${id}`);
			},
			// 视频播放
			onPlayVideo(url) {
				this.$to(`/package/video/video-play/index?url=${url}`);
			},

			// 新增浏览记录
			addBrow(prodId) {
				let date = new Date();
				let duration = parseInt((date.getTime() - this.browTime) / 1000);
				date = formatDate(date, 'YYYY-MM-DD HH:mm:ss');
				this.$resPost('AddUsersBrowse', {
					type: 4,
					product_id: prodId,
					date_time: date,
					duration: duration
				}).catch(() => {});
			},
			// 检测登录
			checkLogin() {
				return this.$login('initPage', this.dataForm.pk_id);
			},
			// 初始化页面数据
			initPage(id) {
				this.$loading();
				this.$resPost('GetProductDetailed', {
						pk_id: id
					})
					.then(({
						data
					}) => {
						if (!data.pk_id || !data.product_stock[0] || data.is_online != 1 || data.status != 1) {
							return Promise.reject();
						}
						if (data.gobal_buyer && data.gobal_buyer != '0') {
							let bol = true
							if (!this.vuex_user.level || this.vuex_user.level == '0') {
								bol = false
							} else {
								let arr = data.gobal_buyer.split(',')
								bol = arr.some((item) => {
									return item == this.vuex_user.level
								})
							}
							if (!bol) {
								this.$hide()
								uni.showModal({
									content: "当前产品您没有查看权限",
									showCancel: false,
									confirmText: '我知道了',
									success: () => {
										this.uniBack()
									}
								})
								return
							}
						}
						uni.setNavigationBarTitle({
							title: data.name || '详情'
						});
						let swipeList = [];
						if (data.video) {
							swipeList.push({
								video: data.video
							});
						}

						if (data.img) {
							data.img.split(',').forEach(item => {
								swipeList.push({
									img: item
								});
							});
						}
						this.swipeList = [].concat(swipeList);
						data.product_stock = (data.product_stock || []).map(item => {
							return {
								...item,
								amount: item.r_price || item.r_price === 0 ? item.r_price : item.amount,
								rebate: item.r_rebate || item.r_rebate === 0 ? item.r_rebate : item.rebate
							};
						});
						data.price = data.product_stock[0].amount;
						data.rebate = data.product_stock[0].rebate;
						data.vip_price = data.product_stock[0].vip_price;
						if (data.product_stock && data.product_stock.length > 1) {
							// 多规格处理：获取最小价格和最大价格
							data.minPrice = data.product_stock[0].amount;
							data.maxPrice = data.product_stock[data.product_stock.length - 1].amount;
							if (data.minPrice == data.maxPrice) {
								data.minPrice = '';
								data.maxPrice = '';
							}
						}
						if (data.type == 2) {
							this.setSeckill(data);
						}
						this.dataForm = {
							...data
						};
						this.customShareParams(); // 设置当前产品页的分享参数
						this.$resPost('GetProductComment', {
							page_size: 3,
							product_id: id,
							type: 1
						}).then(res => {
							res.data = res.data.map(item => {
								if (!item.img) {
									item.img = []
								} else {
									item.img = item.img.split(',');
								}
								return item
							})
							this.dataList = res.data
						})
						this.$hide();
					})
					.catch(() => {
						this.$hide();
						uniModal({
							title: '商品已下架',
							showCancel: false,
							confirmText: '我知道了'
						}).then(() => {
							this.uniBack();
						});
					});
			},
			// 判断秒杀状态
			setSeckill(data) {
				// 秒杀抢购商品：根据产品有效时间获取产品状态：获取状态和距离下个状态的时间
				let start_date = data.start_date;
				let end_date = data.end_date;
				let saleArr = (data.sale_time || '').split(',');
				let sale_startArr = (saleArr[0] || '').split(':');
				let sale_endArr = (saleArr[1] || '').split(':');
				if (data.sale_time) {
					let current = new Date();
					let sale_start = current.setHours(sale_startArr[0], sale_startArr[1], 0);
					let sale_end = current.setHours(sale_endArr[0], sale_endArr[1], 0);
					if (sale_start > start_date) {
						start_date = sale_start;
					}
					if (sale_end < end_date) {
						end_date = sale_end;
					}
				}
				let prodState = getProdStatus(start_date, end_date, false);

				if (prodState.type == 2 && data.sale_time) {
					let tomDate = new Date();
					tomDate.setDate(tomDate.getDate() + 1);
					let tomorrow_start = tomDate.setHours(sale_startArr[0], sale_startArr[1], 0);
					let tomorrow_end = tomDate.setHours(sale_endArr[0], sale_endArr[1], 0);
					if (data.end_date < tomorrow_end) {
						/*这个有没有不大重要，严谨而已*/
						tomorrow_end = data.end_date;
					}
					if (tomorrow_start < data.end_date) {
						// 明天还可以抢购
						prodState = getProdStatus(tomorrow_start, tomorrow_end, false);
					}
				}
				if (prodState.type != 2) {
					// 抢购商品，且未结束开启倒计时
					this.getCountTime(prodState.times);
				}
				this.prodState = {
					...prodState
				};
			},
			// 定时器循环倒计时
			getCountTime(nextTime) {
				if (nextTime >= 0) {
					this.timeObj = countTime(nextTime);
					this.time = setTimeout(() => {
						this.getCountTime(this.timeObj.nextTime);
					}, 1000);
				} else {
					this.initPage(this.dataForm.pk_id);
				}
			},
			// [这个函数名称不能变--pageShare.js]设置当前产品页的分享参数
			customShareParams() {
				if (!this.shareParams.title) {
					let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
					let curRoute = routes[routes.length - 1].route; //获取当前页面路由
					let curParam = routes[routes.length - 1].options; //获取路由参数
					let obj = this.swipeList.find(item => {
						return item.img;
					});
					this.shareParams = {
						title: this.dataForm.name,
						path: curRoute,
						query: curParam,
						imgUrl: obj && obj.img ? obj.img : ''
					};
					// ['hideMenuItems']
					this.onShareByH5().then(() => {
						// wx.hideMenuItems({
						//   menuList: ['menuItem:share:appMessage','menuItem:share:timeline']
						// })
					})
				}
			},
			//收藏切换
			collectChange() {
				this.$u.debounce(
					() => {
						this.checkLogin().then(() => {
							let apiName = this.isFavorite ? 'DeleteUsersFavourite' : 'AddUsersFavourite';
							this.$loading();
							this.$resPost(apiName, {
									type: 4,
									product_id: this.dataForm.pk_id
								})
								.then(() => {
									this.$hide();
									this.$toast(this.isFavorite ? '已取消收藏' : '收藏成功');
									this.dataForm.isFavorite = this.isFavorite ? '0' : '1';
								})
								.catch(() => {
									this.$hide();
								});
						});
					},
					500,
					true
				);
			},
			// 跳转购物车
			linkToCart() {
				this.checkLogin().then(() => {
					this.$to('/package/user/cart/index');
				});
			},
			// 打开规格弹框
			showSpec(type = '') {
				this.$u.debounce(
					() => {
						this.checkLogin().then(() => {
							if (this.dataForm.type == 2) {
								// 抢购:立即购买
								if (this.prodState.type == 2) {
									this.$toast({
										title: '活动已结束'
									});
								} else if (this.prodState.type == 0) {
									this.$toast({
										title: '活动还未开始'
									});
								} else {
									this.specParams.buyType = type;
									this.specVisible = true;
								}
							} else {
								// 普通:立即购买、加入购物车 判断是否在销售时间段内
								this.checktime()
									.then(res => {
										this.specParams.buyType = type;
										this.specVisible = true;
									})
									.catch(res => {
										uniToast(res);
									});
							}
						});
					},
					300,
					true
				);
			},
			// 立即购买
			/**
			 * params 当前规格/价格
			 * */
			buyNow(params) {
				try {
					let url = '/package/product/local/order/index'
					if (this.dataForm.business_pro_id > 0) {
						url += '?business_pro=1'
					}
					let paramsObj = {
						prodType: this.dataForm.type == 2 ? 'seckill' : 'com',
						type: 'prod',
						list: [{
							fk_supplier_id: this.dataForm.fk_supplier_id || 0,
							product_img: this.dataForm.logo,
							express_num: this.dataForm.express_num, // 多少起免邮费
							express_price: this.dataForm.express_price, // 快递费用
							product_freight: this.dataForm.product_freight || [], // 运费模板
							num: params.specNum,
							price: params.specActItem.amount,
							product_id: this.dataForm.pk_id,
							product_name: this.dataForm.name,
							fk_attr_id: params.specActItem.pk_id, // 属性库存id
							standard: params.specActItem.name // 属性库存名称
						}]
					}

					// #ifdef  MP-BAIDU ||  MP-ALIPAY || MP-TOUTIAO	
					this.paramsObj = paramsObj
					this.$to(url)
					// #endif




					// #ifndef MP-ALIPAY || MP-BAIDU || MP-TOUTIAO	
					uniNavigate(url).then(res => {
						res.eventChannel.emit('acceptParams', paramsObj);
					});
					// #endif 
				} catch (e) {
					console.log(e)
				}
			},
			// 跳转其他小程序
			goToMini() {
				let arr = this.dataForm.title.split('ToMini');
				uni.navigateToMiniProgram({
					appId: arr[0],
					path: arr[1],
					success: res => {
						// 打开成功
					}
				});
			}
		}
	};
</script>
<style>
	page {
		background-color: #f5f5f5;
	}
</style>
<style lang="scss" scoped>
	@import 'package/product/common/prodDetail';

	.pricearr {
		width: 250rpx;
	}

	.supplier-box {
		width: 100%;
		padding: 20rpx 0;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.box-left {
			display: flex;
			align-items: center;
			font-size: 26rpx;
			color: #333;

			.left-icon {
				width: 40rpx;
				height: 40rpx;
				font-size: 38rpx;
				margin-right: 10rpx;
			}
		}

		.box-right {
			display: flex;
			align-items: center;
			font-size: 24rpx;
			color: #999;
		}
	}

	.prod_img {
		position: relative;
	}

	/*  #ifdef  MP-ALIPAY	  */
	::v-deep .u-reset-button {
		border: 0 !important;
	}

	/*  #endif  */

	// 跳转其他小程序
	.to_mini {
		margin: 40rpx 0 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.mini_btn {
			width: 80%;
			border: 1rpx solid var(--color);
			border-radius: 14rpx;
			line-height: 66rpx;
			text-align: center;
			color: var(--color);
			background-color: #fff;

			&:active {
				opacity: 0.8;
			}
		}
	}

	.commentbox {}

	.comment-item {
		margin-bottom: 16rpx;
	}

	.ci-avatar {
		width: 70rpx;
		height: 70rpx;
		margin-right: 20rpx;
		border-radius: 50%;
		overflow: hidden;
	}

	.ci-info {
		flex: 1;
		width: 100%;

		.ci-date {
			font-size: 24rpx;
			margin-top: 4rpx;
		}
	}

	.ci-b {
		width: 100%;
		padding-left: 90rpx;
		margin-top: 10rpx;
		font-size: 28rpx;
	}

	.ci-img {
		width: 100%;
		padding-left: 90rpx;
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		margin-top: 10rpx;

		.ci-img-item {
			width: 100rpx;
			height: 100rpx;
			margin-right: 5px;
			margin-bottom: 5px;
		}
	}
</style>
